# -*- coding: utf-8 -*-
'''
    :file: app.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/04/02 10:52:57
'''
from flask import Flask, jsonify
from flask.globals import request, g
from flask_cors import CORS
from time import time
import os

app = Flask(__name__)
CORS(app)
# 模拟数据库
database = [{
    'username': 'admin',
    'password': 'admin'
}, {
    'username': 'test',
    'password': 'test'
}]

# 格式化响应体
def make_res(status: int = 200, msg: str = 'ok', data: any = None) -> dict:
    return {
        "status": status,
        "msg": msg,
        "data": data
    }


@app.route("/")
def index():
    return f'<h1>index</h1>'


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.get_json().get('user')
        password = request.get_json().get('password')
        for user in database:
            if user['username'] == username and user['password'] == password:
                return jsonify(make_res(data={
                    "user": username,
                    'token': 'hash_token'
                }))
        return jsonify(make_res(status=-1, msg='用户不存在'))

    return 'login-get'


@app.route('/getInfo')
def get_info():
    if not g.login:
        return jsonify(make_res(status=-1, msg='未登录'))
    dirs = os.listdir()

    return jsonify(make_res(data={
        'ts': time(),
        'dirs': dirs
    }))


@app.before_request
def check_token():
    g.login = False
    token = dict(request.headers).get('Authorization')

    if token == 'Bearer hash_token':
        g.login = True
